<template>
  <div id="eqMaintainOrderDiv">
    <Breadcrumb content="点检任务管理" />
    <div class="bodyContent">
      <Splitpanes horizontal class="horizontalLine">
        <Pane size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findSpotcheckTaskList" @keyup="keyupEnter" @search-click="findSpotcheckTaskList()"></vxe-input>

              <span style="margin-left: 5px; margin-right: 5px">状态</span
              ><el-radio-group v-model="searchForm.taskStatus" size="small" @change="changeStatus">
                <el-radio-button label="">全部</el-radio-button>
                <el-radio-button label="0">待检</el-radio-button>
                <el-radio-button label="5">在检</el-radio-button>
                <el-radio-button label="10">已检</el-radio-button>
              </el-radio-group>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="查询" :loading="tloading" @click="findSpotcheckTaskList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增点检任务" @click="addMaintainDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchPatrolTask"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <div style="height: calc(100% - 32px)">
              <vxe-table ref="patrolTaskTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="spotcheckTaskList" :loading="tloading" @current-change="patrolTaskRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                <vxe-column type="seq" width="30" title=""></vxe-column>
                <vxe-column type="checkbox" width="20"></vxe-column>
                <vxe-column field="code" title="编号"> </vxe-column>
                <vxe-column field="code" title="编号"> </vxe-column>
                <vxe-column field="name" title="名称"> </vxe-column>
                <vxe-column field="status" title="点检状态">
                  <template #default="{ row }">
                    <el-tag :type="getTagType(row)">
                      <span>{{ getTaskStatusDesc( row.status) }}</span>
                    </el-tag>
                    <el-tag type="danger" v-if="row.maintainStatus!='10'&&row.overdue>0">
                      逾期{{row.overdue}}天
                    </el-tag>
                  </template>
                </vxe-column>
                <vxe-column field="beginTime" title="开始时间"> </vxe-column>
                <vxe-column field="endTime" title="结束时间"> </vxe-column>
                <vxe-column title="操作" fixed="right" width="90" align="center">
                  <template #default="{ row }">
                    <vxe-button type="text" status="primary" icon="vxe-icon-edit" content="编辑" @click="editTaskShow({ row })"></vxe-button>
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
            <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
        <Pane size="40">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="点检明细" name="first">
              <div class="tableBody">
                <vxe-table ref="maintainDetailTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="taskEqList" :loading="ploading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                  <vxe-column type="seq" width="30" title=""></vxe-column>
                  <vxe-column field="equiptCode" title="设备编号"> </vxe-column>
                  <vxe-column field="equiptName" title="设备名称"> </vxe-column>
                  <vxe-column field="specification" title="规格型号"> </vxe-column>
                  <vxe-column field="status" title="点检内容">
                    <template #default="{ row }">
                      <span>
                        <el-tag v-for="(item, index) in row.patrolTaskEqStList" :key="index">{{ item.standardName }}</el-tag>
                      </span>
                    </template>
                  </vxe-column>
                  <vxe-column field="checkResult" title="结果"></vxe-column>
                  <vxe-column field="noPass" title="不通过部分"></vxe-column>
                  <vxe-column field="noCheck" title="未检部分"></vxe-column>
                  <vxe-column title="操作" fixed="right" width="90" align="center">
                    <template #default="{ row }">
                      <vxe-button type="text" status="primary" icon="vxe-icon-edit" content="编辑" @click="editTaskEqStItShow({ row })"></vxe-button>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
  <el-dialog title="点检内容" v-model="showTaskEqStItDialog" :modal-append-to-body="false" :close-on-click-modal="false" @closed="closeTaskEqStItDialog" width="1000px">
    <vxe-table class="mb10" border ref="itemTable" :data="taskEqStItList" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
      <vxe-column label="操作" align="center" width="250">
        <template #default="{ row }">
          <el-input v-if="row.projectType === 'txt'" v-model="row.checkResultTest" @blur="inputBlurHandler(row)" type="text" placeholder="请输入点检结果"></el-input>

          <el-radio-group v-if="row.projectType === 'radio'" v-model="row.checkResultTest">
            <div v-for="i in row.normalValue.split(';')" :key="i" class="check-row-inline">
              <el-radio :label="i" @click.native.prevent="changRradioItem(row, i)" class="inst-checkboxClazz">{{ i }} </el-radio>
            </div>
            <div v-for="i in row.exceptValue.split(';')" :key="i" class="check-row-inline">
              <el-radio :label="i" @click.native.prevent="changRradioItem(row, i)" class="inst-checkboxClazz">{{ i }} </el-radio>
            </div>
          </el-radio-group>
          <el-checkbox-group v-if="row.projectType === 'check'" @change="changCheckbox(row)" v-model="row.checkResultTestList">
            <div v-for="i in row.normalValue.split(';')" :key="i" class="check-row-inline">
              <el-checkbox :label="i" class="inst-checkboxClazz">{{ i }}</el-checkbox>
            </div>
            <div v-for="i in row.exceptValue.split(';')" :key="i" class="check-row-inline">
              <el-checkbox :label="i" class="inst-checkboxClazz">{{ i }}</el-checkbox>
            </div>
          </el-checkbox-group>
        </template>
      </vxe-column>
      <vxe-column field="projectName" title="项目名称" align="center"></vxe-column>
      <vxe-column field="maxValue" title="参考上限" align="center"></vxe-column>
      <vxe-column field="mixValue" title="参考下限" align="center"></vxe-column>
      <vxe-column field="checkResult" title="点检结果" align="center"></vxe-column>
      <vxe-column field="isNormal" title="是否异常" align="center"></vxe-column>
    </vxe-table>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveTaskEqStIt()">保 存</el-button>
      <el-button @click="closeTaskEqStItDialog()">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
let { proxy }: any = getCurrentInstance();
import { AppStore } from '@/stores/store';
import { IsEmpty } from '@/utils/common'; //'../../../stores/store';

let store = AppStore();

// 全局变量定义区 ==========
let searchForm = {
  searchValue: '',
  taskStatus:''
};
let tloading = ref(false); //加载状态
let ploading = ref(false); //加载状态
let showTaskEqStItDialog = ref(false); //加载状态

let spotcheckTaskList: any = reactive([]);
let taskEqList: any = reactive([]);
let maintainStatusList: any = reactive([]); //选择字典
let maintainTypeList: any = reactive([]); //选择字典
let inspectionStatusList: any = reactive([]); //选择字典
let verifylList: any = reactive([]);
let taskEqStItList: any = reactive([]);

let eqPatrolTask: any = ref({});
let activeName = ref('first');

let verifyform = reactive({
  maintainStatus: '15'
});
// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  getDictItemsList(); //批量获取字典
  findSpotcheckTaskList(); // 获取质控规则表格数据
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['maintainType', 'maintainStatus', 'inspectionStatus'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const maintainTypes = dictTreeTypeItems.data.find((item) => item.code === 'maintainType');
  maintainTypeList.push(...maintainTypes.detailDataList);
  const maintainStatues = dictTreeTypeItems.data.find((item) => item.code === 'maintainStatus');
  maintainStatusList.push(...maintainStatues.detailDataList);
  const inspectionStatus = dictTreeTypeItems.data.find((item) => item.code === 'inspectionStatus');
  inspectionStatusList.push(...inspectionStatus.detailDataList);
}

function getTaskStatusDesc(scope: any) {
  for (const item of inspectionStatusList) {
    if (scope == item.code) {
      return item.name;
    }
  }
}

function changeStatus(item: any) {
  searchForm.taskStatus=item;
  findSpotcheckTaskList();
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findSpotcheckTaskList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findSpotcheckTaskList();
}
function findSpotcheckTaskList() {
  tloading.value = true;
  spotcheckTaskList.length = 0; //放入数据前清空数据
  const url = '/api/eq/spotcheckTask/findSpotcheckTaskPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        status:searchForm.taskStatus,
        seachValue: searchForm.searchValue,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      spotcheckTaskList.push(...res.data.records);
      page.totalResult = res.data.total;
      const kn = spotcheckTaskList.find((k: any) => k.id == eqPatrolTask.value.id);
      if (IsEmpty(kn)) {
        patrolTaskRowClick({ row: spotcheckTaskList[0] }); //默认选中第一条数据
      } else {
        patrolTaskRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function patrolTaskRowClick({ row }: any) {
  if (IsEmpty(row)) {
    eqPatrolTask.value = {};
    taskEqList.length = 0; //放入数据前清空数据
  } else {
    (proxy.$refs.patrolTaskTableRef as any).setCurrentRow(row);
    eqPatrolTask.value = row;
    if (activeName.value == 'first') {
      findMaintainDetailList();
    }
  }
}

function tabHandleClick(tab) {
  if (tab.index == 0) {
    findMaintainDetailList();
  }
}

function findMaintainDetailList() {
  ploading.value = true;
  taskEqList.length = 0; //放入数据前清空数据
  const url = '/api/eq/spotcheckTaskEq/findSpotcheckTaskEqList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        taskId: eqPatrolTask.value.id
      }
    })
    .then((res: any) => {
      if (res.status.code === 1) {
        taskEqList.push(...res.data);
      }
      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function deleteBatchPatrolTask() {
  const sltMaintainOrders = (proxy.$refs.patrolTaskTableRef as any).getCheckboxRecords();
  if (!(sltMaintainOrders.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy.$XModal.confirm('您确定要删除吗？').then((type) => {
      if (type === 'confirm') {
        //后台删除数据
        const delMaintainOrderList = sltMaintainOrders.filter((p: any) => !IsEmpty(p.id));
        if (delMaintainOrderList.length > 0) {
          const url = '/api/eq/spotcheckTask/deleteSpotcheckTask';
          proxy.$http
              .post(url, delMaintainOrderList)
              .then((res: any) => {
                findSpotcheckTaskList(); // 获取检验仪器表格数据
                VxeMessage('删除成功!', VxeNotifyType.success);
              })
              .catch((err: any) => {
                VxeMessage(err, VxeNotifyType.error);
              });
        }
      }
    })
  }
}
function editTaskShow({ row }) {
  const data = {
    id: row.id,
    url: '/spotcheckTask'
  };
  proxy.$router.push({ path: '/spotcheckTaskEdit', query: data });
}

function addMaintainDialog() {
  const data = {
    url: '/spotcheckTask'
  };
  proxy.$router.push({ path: '/spotcheckTaskEdit', query: data });
}

function executeMaintain(row: any) {
  const data = {
    id: row.id,
    pageIndex: page.currentPage.toString(),
    pageSize: page.pageSize.toString(),
    url: '/eqMaintainOrder'
  };
  proxy.$router.push({ path: '/eqMaintainEdit', query: data });
}

async function deleteVerifyMaintain(row: any) {
  const $table = proxy.$refs.verifyTableRef as any;
  if ($table) {
    let cnt = verifylList.findIndex((a: any) => a.id == row.id);
    if (cnt > -1) {
      await $table.remove(row);
      verifylList.splice(cnt, 1);
    }
  }
}
function formatCommon(arr: any, value: any) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
//编辑点检明细
function editTaskEqStItShow({ row }) {
  taskEqStItList.length = 0;
  const url = '/api/eq/spotcheckTaskEqStIt/findSpotcheckTaskEqStItList';
  const data = {
    taskEqId: row.id
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res.status.code !== 1) {
        proxy.$alert(res.status.msg, '提示');
      } else {
        taskEqStItList.push(...res.data);
        showTaskEqStItDialog.value = true;
      }
    })
    .catch((err) => {
      proxy.$alert(err, '提示');
    });
}

function saveTaskEqStIt() {
  showTaskEqStItDialog.value = false;
  const url = '/api/eq/spotcheckTaskEqStIt/saveOrUpdateTaskEqStIt';
  proxy.$http
    .post(url, taskEqStItList)
    .then((res: any) => {
      if (res.status.code === 1) {
        if (status === '5') {
          VxeMessage('提交成功', VxeNotifyType.success);
        } else {
          VxeMessage('保存成功', VxeNotifyType.success);
        }
        //刷新列表
        findSpotcheckTaskList();
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err) => {});
}
function closeTaskEqStItDialog() {
  taskEqStItList.length = 0;
  showTaskEqStItDialog.value = false;
}
function inputBlurHandler(scope) {
  if (scope.checkResultTest) {
    scope.checkResult = scope.checkResultTest;
    const maxValue = parseFloat(scope.maxValue);
    const mixValue = parseFloat(scope.mixValue);
    const checkResult = parseFloat(scope.checkResult);
    if (checkResult <= maxValue && checkResult >= mixValue) {
      scope.isNormal = '正常';
    } else {
      scope.isNormal = '异常';
    }
  } else {
    scope.checkResult = '';
    scope.checkResultTest = '';
    scope.isNormal = '';
  }
}
function changRradioItem(scope, item) {
  item === scope.checkResultTest ? (scope.checkResultTest = '') : (scope.checkResultTest = item);
  scope.checkResult = scope.checkResultTest;
  if (scope.checkResultTest === '') {
    scope.isNormal = '';
  } else {
    const i = scope.normalValue.indexOf(scope.checkResultTest);
    if (i >= 0) {
      scope.isNormal = '正常';
    } else {
      const j = scope.exceptValue.indexOf(scope.checkResultTest);
      if (j >= 0) {
        scope.isNormal = '异常';
      } else {
        scope.isNormal = '';
      }
    }
  }
}
function changCheckbox(scope) {
  if (scope.checkResultTestList && scope.checkResultTestList.length > 0) {
    scope.checkResult = scope.checkResultTestList.join(';');
    scope.checkResultTest = scope.checkResultTestList.join(';');
    const ycList = scope.exceptValue.split(';');
    let isHve = false;
    for (const yc of ycList) {
      const i = scope.checkResultTest.indexOf(yc);
      if (i >= 0) {
        isHve = true;
      }
    }
    if (isHve) {
      scope.isNormal = '异常';
    } else {
      scope.isNormal = '正常';
    }
  } else {
    scope.checkResult = '';
    scope.checkResultTest = '';
    scope.isNormal = '';
  }
}
function getTagType(row: any) {
  const status = row.status;
  if (status === '0') {
    return 'warning';
  } else if (status === '5') {
    return 'danger';
  } else if (status === '10') {
    return 'success';
  }
}

</script>

<style lang="scss" scoped>
#eqMaintainOrderDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
    }
    .horizontalLine {
      :deep(.splitpanes__splitter) {
        background-color: $base-white;
      }
    }

    // 中间table表格
    .tableBody {
      height: calc(100% - 40px);
    }
    // 质控靶值设定弹框表格
    .tableTargetBody {
      height: 600px;
      .tableTargetBodyRight {
        height: calc(100% - 2px);
        border: 1px solid #e8eaec;

        .closeBtn {
          margin-left: 720px;
        }
      }
    }

    // 右侧保存按钮
    .saveBtn {
      float: right;
      margin: 5px 10px;
    }
    .el-form {
      padding-right: 15px;
      .el-form-item--large {
        margin-bottom: 10px;
      }
      .el-button {
        padding: 5px 2px !important;
      }
      :deep(.el-input__inner) {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;
      padding: 10px;
    }
    // 最右侧质控项目设定表格
    .tableBox {
      height: calc(100% - 40px);
    }
  }

  :deep(.el-tabs) {
    height: 100%;
    .el-tabs__content {
      height: calc(100% - 70px);
      .el-tab-pane {
        height: 100%;
      }
    }
  }
}
</style>
